/**
 * Created by dev-001 on 2017/3/2.
 * 资源文件
 */
import mongoose from 'mongoose';
import path from 'path';
import url from 'url';
import { ExamCat, staticServ } from '../../config/index';
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

const AttachmentSchema = new Schema({
    name: String, //原文件名称
    uuid: String,
    path: String, //文件所在目录，结合文件服务器
    type: String, //文件类型,word pfd等
    size: String, //文件大小
    qiniu: String,
    height: String,
    width: String,
    status: {
        type: Boolean,
        default: true
    },
    createdAt: Date,
    updatedAt: Date
},{
    toObject: {
        virtuals: true
    },
    toJSON: {
        virtuals: true
    }
});

AttachmentSchema.virtual('fullPath').get(function () {
    if(!!this.path) {
        return url.resolve(staticServ.host, this.path);
    }
    return this.path;
});

AttachmentSchema.virtual('localPath').get(function () {
    if(!!this.path) {
        return path.join(ExamCat.base(), this.path);
    }
    return this.path;
});

AttachmentSchema.virtual('hostPath').get(function () {
    if(!!this.path) {
        return url.resolve(staticServ.host, this.path);
    }
    return this.path;
});

AttachmentSchema.virtual('qiniuPath').get(function () {
    if(!!this.path) {
        return url.resolve(staticServ.qiniuhost, this.path);
    }
    return this.path;
});


AttachmentSchema.pre('save', function(next) {
    console.log('presave', this.path, !!this.path && this.path.indexOf(ExamCat.base()) > -1)
    if(!!this.path && this.path.indexOf(ExamCat.base()) > -1) {
        this.path = ExamCat.relative(this.path);
    }
    next();
});

export default mongoose.model('Attachment', AttachmentSchema);